<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../elementui/vue.min.js"></script>
    <link rel="stylesheet" href="../elementui/index.css">
    <script src="../elementui/index.js"></script>


</head>
<body>
<div id="app">

    <el-row>
        <img :src="objUrl" width="300" alt="img"/>
    </el-row>
    <el-row>
        <canvas ref="canvasRef" width="100" height="100" style="border: 1px solid red">
            浏览器不支持canvas
        </canvas>
    </el-row>
    <el-row>

        <el-button @click="openFile" type="primary">打开</el-button>
        <el-button @click="onSaveFile" type="primary">保存</el-button>

    </el-row>

</div>

<script type="module">
    new Vue({
        el: '#app',
        data: {
            objUrl: "",
            handle: {},
        },
        methods: {
            setFileHandler(handle) {
                this.handle = handle
            },

            async openFile() {
                const context = this.$refs.canvasRef.getContext("2d")
                let [fileHandle] = await window.showOpenFilePicker();
                const f = await fileHandle.getFile()
                const url = URL.createObjectURL(f)
                this.objUrl = url;
                const image = new Image()
                image.width = 100;
                image.onload = () => {
                    context.drawImage(image, 0, 0, 100, 100);
                    const data = context.getImageData(0, 0, 100, 100);
                    this.color2Gray(data)
                    context.putImageData(data, 0, 0, 0, 0, data.width, data.height);
                }
                image.src = url;
            },
            color2Gray(imgData) {
                for (let index = 0, i = 0; index = 0, i < imgData.width; i++) {
                    for (let j = 0; j < imgData.height; j++, index += 4) {
                        const red = imgData.data[index];
                        const green = imgData.data[index + 1];
                        const blue = imgData.data[index + 2];
                        const ave = (red + green + blue) / 3;
                        imgData.data[index] = ave;
                        imgData.data[index + 1] = ave;
                        imgData.data[index + 2] = ave;
                    }
                }
            },
            async saveFile(handle) {
                if (!handle) return;
                const stream = await this.handle.createWritable();
                this.$refs.canvasRef.toBlob(async (b) => {
                    if (!b) return;
                    await stream.write(b);
                    await stream.close();
                })
            },
            async onSaveFile() {
                let fileHandle = await window.showSaveFilePicker();
                saveFile(fileHandle);
            },
        }
    })
</script>
</body>
</html>
